package cn.lili.modules.permission.serviceimpl;

import cn.hutool.core.text.CharSequenceUtil;
import cn.lili.common.enums.ResultCode;
import cn.lili.common.exception.ServiceException;
import cn.lili.common.security.AuthUser;
import cn.lili.common.security.context.UserContext;
import cn.lili.common.security.token.Token;
import cn.lili.common.utils.BeanUtil;
import cn.lili.common.utils.StringUtils;
import cn.lili.common.vo.PageVO;
import cn.lili.modules.member.entity.dos.Member;
import cn.lili.modules.member.entity.dos.Partner;
import cn.lili.modules.member.service.MemberService;
import cn.lili.modules.member.service.PartnerService;
import cn.lili.modules.permission.entity.dos.*;
import cn.lili.modules.permission.entity.dto.AdminUserDTO;
import cn.lili.modules.permission.entity.vo.AdminUserVO;
import cn.lili.modules.permission.entity.vo.AgentVO;
import cn.lili.modules.permission.entity.vo.StoreUserVO;
import cn.lili.modules.permission.mapper.AdminUserMapper;
import cn.lili.modules.permission.mapper.RoleMapper;
import cn.lili.modules.permission.mapper.StoreUserMapper;
import cn.lili.modules.permission.service.*;
import cn.lili.modules.store.entity.dos.Store;
import cn.lili.modules.store.entity.vos.StoreVO;
import cn.lili.modules.store.mapper.StoreMapper;
import cn.lili.modules.system.aspect.annotation.SystemLogPoint;
import cn.lili.modules.system.token.ManagerTokenGenerate;
import cn.lili.mybatis.util.PageUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 商家端用户业务层实现
 *
 * @author Chopper
 * @since 2020/11/17 3:46 下午
 */
@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
public class StoreUserServiceImpl extends ServiceImpl<StoreUserMapper, StoreUser> implements StoreUserService {

	@Autowired
	private RoleMapper roleMapper;
	@Autowired
	private RoleService roleService;
	@Autowired
	private UserRoleService userRoleService;

	@Override
	public IPage<StoreUserVO> StoreUserPage(Page initPage, QueryWrapper<StoreUser> initWrapper) {
		// 获取当前角色下级所有的角色所分配的用户
		AuthUser currentUser = UserContext.getCurrentUser();
		StoreUser storeUser = this.baseMapper.selectById(currentUser.getId());
		// 不是超级管理员则获取当用户分配的前角色以和以下的角色
		List listIn = new ArrayList<>();
		List<Role> list = roleMapper.ListRole(storeUser.getRoleIds(), "1"); // 0平台 1商家
		list.forEach(item -> {
			listIn.add(item.getId());
		});
		initWrapper.in("role_ids", listIn);
		initWrapper.eq("is_super", false);
		Page<StoreUser> StoreUserPage = page(initPage, initWrapper);
		List<Role> roles = roleService.list();
		List<StoreUserVO> result = new ArrayList<>();
		StoreUserPage.getRecords().forEach(storeAdminUser -> {
			StoreUserVO storeUserVO = new StoreUserVO(storeAdminUser);
			if (!StringUtils.isEmpty(storeAdminUser.getRoleIds())) {
				try {
					List<String> memberRoles = Arrays.asList(storeAdminUser.getRoleIds().split(","));
					storeUserVO.setRoles(roles.stream().filter(role -> memberRoles.contains(role.getId()))
							.collect(Collectors.toList()));
				} catch (Exception e) {
					log.error("填充部门信息异常", e);
				}
			}
			result.add(storeUserVO);
		});
		Page<StoreUserVO> pageResult = new Page(StoreUserPage.getCurrent(), StoreUserPage.getSize(),
				StoreUserPage.getTotal());
		pageResult.setRecords(result);
		return pageResult;
	}

	@Override
	public void deleteCompletely(List<String> ids) {
		// 彻底删除超级管理员
		this.removeByIds(ids);
		// 删除管理员角色
		QueryWrapper<UserRole> queryWrapper = new QueryWrapper<>();
		queryWrapper.in("user_id", ids);
		userRoleService.remove(queryWrapper);
	}

	@Override
	public void resetPassword(List<String> ids) {
		LambdaQueryWrapper<StoreUser> lambdaQueryWrapper = new LambdaQueryWrapper();
		lambdaQueryWrapper.in(StoreUser::getId, ids);
		List<StoreUser> adminUsers = this.list(lambdaQueryWrapper);
		String password = StringUtils.md5("123456");
		String newEncryptPass = new BCryptPasswordEncoder().encode(password);
		if (null != adminUsers && adminUsers.size() > 0) {
			adminUsers.forEach(item -> item.setPassword(newEncryptPass));
			this.updateBatchById(adminUsers);
		}
	}

}
